<template>
  <view class="page">
    <view class="commentinfo" v-if="comment">
      <view class="w100 mb2" v-if="comment.iscase">
        <view class="resultstime" style="background-color: #fff7f2">
          <view class="resultstime-text">
            <view class="header-context" style="margin-bottom: 12rpx">
              <view class="resultstime-title"> {{ $t("推 荐 人") }} </view>
              <view class="resultstime-context">
                {{ comment.caseusername }}
              </view>
            </view>
            <view>
              <view class="resultstime-title" style="margin-bottom: 12rpx">
                {{ $t("推荐理由") }}
              </view>
              <view class="resultstime-context">
                {{ comment.casecontext }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="header">
        <view class="poiName">{{ comment?.deptname }}</view>
        <view class="steps" id="steps">
          <uv-steps
            :current="commentsteps"
            activeColor="#ff724c"
            inactiveIcon="question-circle"
            activeIcon="checkmark-circle"
          >
            <uv-steps-item
              :customStyle="{}"
              v-for="(v, i) in commentstepsoption"
              :key="i"
            >
              <template v-slot:title>
                <text class="uv-text1">{{ $t(v.name) }}</text>
              </template>
              <template v-slot:desc>
                <text class="uv-text1">{{ v.time }}</text>
              </template>
            </uv-steps-item>
          </uv-steps>
        </view>
      </view>

      <view class="w100 mb2" v-if="comment.type !== 'tiancai'">
        <Item :data="comment" :clickuserAvatar="clickuserAvatar"></Item>
      </view>
      <view class="mb2" style="width: 100%; padding-bottom: 30rpx" v-else>
        <Tiancaiitem
          :data="comment"
          :clickuserAvatar="clickuserAvatar"
        ></Tiancaiitem>
      </view>
      <view class="w100 mb2">
        <view class="header-icon">
          <uv-icon
            name="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/%E4%BA%BA%E5%91%98%403x.png"
            color="#2979ff"
            size="24"
          ></uv-icon>
          <text class="header-icon-text">{{ $t("已读人员") }}</text>
        </view>
        <view class="header-button">
          <view v-for="v in commentuserwatch" :key="v.id">
            <uv-button
              plain
              hairline
              :custom-style="_miniButton"
              :customTextStyle="_defaultTextjustify"
              color="#748ee2"
              size="small"
              :text="v.tenant_user?.user?.name"
            ></uv-button>
          </view>
        </view>
      </view>
      <view
        class="w100 mb2"
        v-if="comment.replyList?.filter((c) => c.content).length"
      >
        <storereplyVue :data="comment"></storereplyVue>
      </view>
      <view
        class="w100 mb2"
      >
        <view class="header-icon">
          <uv-icon
            name="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/chat-gpt.png"
            color="#2979ff"
            size="24"
          ></uv-icon>
          <text class="header-icon-text">AI标签</text>
        </view>
        <view class="header-button">
          <view v-for="v in comment.aiidentifycommentlabel" :key="v.id">
            <uv-button
              plain
              hairline
              :custom-style="_miniButton"
              :customTextStyle="_defaultTextjustify"
              color="#748ee2"
              size="small"
              :text="v.aiidentifylabel?.name"
            ></uv-button>
          </view>
          <view v-for="v in comment.product" :key="v.id">
            <uv-button
              plain
              hairline
              :custom-style="_miniButton"
              :customTextStyle="_defaultTextjustify"
              color="#748ee2"
              size="small"
              :text="`${v.aiidentifylabelname} - ${v.name}`"
            ></uv-button>
          </view>
        </view>
        <view class="resultstime-button">
          <uv-button
            :custom-style="submitButton"
            @click="
              navigateTo('/pages/comment/createaiidentifycomment?id=' + id)
            "
            >{{ $t("编辑AI标签") }}</uv-button
          >
        </view>
      </view>
      <view class="w100 mb2">
        <identify
          :data="comment"
          :identifylabel="identifylabel"
          :bottonshow="!!permmenu.find((e) => e.name === '鉴定操作')"
        >
        </identify>
      </view>
      <view class="w100 mb2" v-if="comment.identifycomment?.isfeedback">
        <view class="resultstime">
          <view class="header-avatar">
            <view>
              <uv-avatar
                src="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/%E9%97%A8%E5%BA%97%403x.png"
                size="24"
                shape="square"
              ></uv-avatar>
            </view>
            <view class="header_right">
              <view class="top">
                <view>{{ $t("门店反馈") }} </view>
              </view>
              <view class="top2" v-if="comment.resultstime">
                <view>{{
                  dayjs(comment.resultstime).format("YYYY-MM-DD HH:mm:ss")
                }}</view>
              </view>
            </view>
          </view>
          <view class="resultstime-text" v-if="comment.resultstime">
            <view class="mb3">
              <view class="resultstime-title mb2">
                {{ feedbackset.customer }}
              </view>
              <view class="resultstime-context">{{
                comment.CustomerFeedback
              }}</view>
              <view class="context-voice">
                <view
                  class="context-voice-mic"
                  @click="play(comment.CustomerFeedbackvoice, 0)"
                  v-if="comment.CustomerFeedbackvoice"
                >
                  <uv-icon
                    custom-prefix="custom-icon"
                    color="#ffffff"
                    :name="playing === 0 ? lujing : bofang"
                    size="14"
                  ></uv-icon>
                </view>
              </view>
            </view>
            <view class="mb3">
              <view class="resultstime-title mb2">
                {{ feedbackset.method }}
              </view>
              <view class="resultstime-context">{{ comment.results }}</view>
              <view class="context-voice">
                <view
                  class="context-voice-mic"
                  @click="play(comment.resultsvoice, 1)"
                  v-if="comment.resultsvoice"
                >
                  <uv-icon
                    custom-prefix="custom-icon"
                    color="#ffffff"
                    :name="playing === 1 ? lujing : bofang"
                    size="14"
                  ></uv-icon>
                </view>
              </view>
            </view>
            <view class="mb3" v-if="comment.customerremarks">
              <view class="resultstime-title mb2">
                {{ $t("顾客信息") }}
              </view>
              <view class="resultstime-context">{{
                comment.customerremarks
              }}</view>
            </view>
            <view
              v-if="
                comment.resultsFile?.filter(
                  (c) => !c.type || c.type === 'image'
                ).length
              "
            >
              <uv-album
                :urls="
                  comment.resultsFile
                    .filter((c) => !c.type || c.type === 'image')
                    .map((e) => geturl(e.url))
                "
                :multipleSize="'calc(30vw - 16rpx)'"
              ></uv-album>
            </view>
            <view
              v-else-if="
                comment.resultsFile?.filter((c) => c.type === 'video').length
              "
            >
              <uvVideo
                :file="comment.resultsFile?.filter((c) => c.type === 'video')"
              ></uvVideo>
            </view>
          </view>
          <view
            class="resultstime-button"
            v-if="permmenu.find((e) => e.name === '门店反馈')"
          >
            <uv-button
              :custom-style="submitButton"
              @click="navigateTo('/pages/comment/commentresults?id=' + id)"
              >{{ $t("编辑反馈") }}</uv-button
            >
          </view>
        </view>
      </view>

      <view class="w100 mb2">
        <view class="header-icon">
          <uv-icon
            name="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/%E8%AE%A8%E8%AE%BA%403x.png"
            color="#2979ff"
            size="24"
          ></uv-icon>
          <text class="header-icon-text">{{ $t("内部讨论") }}</text>
        </view>
        <discuss
          v-if="commentuser.length"
          :commentuser="commentuser"
          :start="start"
        ></discuss>
        <view v-else class="bg-commenthistorycomputed">
          {{ $t("暂无讨论") }}
        </view>
        <view
          class="header-button"
          v-if="permmenu.find((e) => e.name === '参与讨论')"
        >
          <view class="resultstime-button">
            <uv-button
              :custom-style="submitButton"
              :text="$t('发起讨论')"
              @click="
                navigateTo(
                  `/pages/comment/commentuser?id=${comment.id}&feedbackId=${comment.feedbackId}`
                )
              "
            ></uv-button>
          </view>
        </view>
      </view>

      <view class="w100 mb2" v-if="commenthistorycomputed.length">
        <view class="header-icon">
          <uv-icon
            name="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/%E8%AE%B0%E5%BD%95%403x.png"
            color="#2979ff"
            size="24"
          ></uv-icon>
          <text class="header-icon-text">{{ $t("评价改动") }}</text>
        </view>
        <view class="header-button">
          <commenthistorycomputedvue
            class="flex1"
            :commenthistorycomputed="commenthistorycomputed"
          >
          </commenthistorycomputedvue>
        </view>
      </view>

      <view class="w100 mb2">
        <view class="header-icon">
          <uv-icon
            name="https://mxzj-translate.oss-cn-chengdu.aliyuncs.com/catv2/appfile/image/img/%E6%A1%88%E4%BE%8B%403x.png"
            color="#2979ff"
            size="24"
          ></uv-icon>
          <text class="header-icon-text">{{ $t("学习案例") }}</text>
        </view>
        <view
          class="resultstime"
          v-if="comment.iscase"
          style="background-color: transparent"
        >
          <view class="resultstime-text">
            <view class="header-context" style="margin-bottom: 12rpx">
              <view class="resultstime-title">{{
                $t("该评论被选为了学习案例")
              }}</view>
              <view class="resultstime-context"
                >{{ dayjs(comment?.casetime).format("YYYY-MM-DD HH:mm:ss") }}
              </view>
            </view>
          </view>
        </view>
        <view
          v-else-if="permmenu.find((e) => e.name === '设置案例')"
          class="resultstime-button"
        >
          <uv-button
            :custom-style="submitButton"
            :text="$t('设为案例')"
            @click="
              navigateTo(
                `/pages/comment/casecomment?id=${comment.id}&feedbackId=${comment.feedbackId}`
              )
            "
          ></uv-button>
        </view>
      </view>
      <view class="info-footer">
        <uv-button
          :custom-style="defaultButton"
          :text="$t('返回列表')"
          @click="navigateback"
        ></uv-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import api, { apiget } from "@/api";
import Item from "@/components/comment/item.vue";
import Tiancaiitem from "@/components/comment/tiancaiitem.vue";
import storereplyVue from "@/components/comment/storereply.vue";
import identify from "@/components/comment/identify.vue";
import discuss from "@/components/comment/discuss.vue";
import commenthistorycomputedvue from "@/components/comment/commenthistorycomputed.vue";
import uvVideo from "@/components/uv-video/index.vue";
import { onLoad, onPullDownRefresh, onShow } from "@dcloudio/uni-app";
import { uniqBy } from "lodash-es";
import dayjs from "dayjs";
import { ref } from "vue";
import { computed } from "vue";
import { navigateTo } from "@/util/navigator";
import {
  submitButton,
  defaultButton,
  miniButton,
  defaultTextjustify,
} from "@/util/style";
import { assign, forEach, isNumber } from "lodash-es";
import { onMounted, inject } from "vue";
import { lujing, bofang } from "@/util/data";
import { dhms, geturl } from "@/util";
import { useI18n } from "vue-i18n";
const permmenu = inject<{ name: string }[]>("permmenu", []);
const feedbackset = inject("feedbackset", {
  customer: "顾客反馈",
  customershow: 1,
  customerrequired: 1,
  method: "处理方法和结果",
  methodshow: 1,
  methodrequired: 1,
  usershow: 0,
  userrequired: 0,
});
const id = ref("");
const comment = ref<Eps.BaseUserCommentEntity>();

const $t = useI18n().t;

const _miniButton = assign({}, miniButton, {
  background: "#f8f9fd",
  padding: "0px 12px",
});

const _defaultTextjustify = assign({}, defaultTextjustify);

onLoad(async (query) => {
  id.value = query?.id;
  uni.setStorageSync("to", "");
  const e = apiget("/wechat/index/online");
  if (!e) {
    uni.setStorageSync("to", `/pages/comment/commentinfo?id=${id.value}`);
    uni.switchTab({
      url: "/pages/user/index",
    });
  }
});

onShow(() => {
  start();
});

const commentuser = ref<Eps.commentuserEntity[]>([]);
const commentuserwatch = ref<Eps.commentuserwatchEntity>([]);
const commenthistory = ref<Eps.BaseUserCommentEntity[]>([]);
const commentfeedback = ref<Eps.BaseUserCommentEntity[]>([]);
const identifylabel = ref<Eps.identifylabelEntity[]>([]);

const innerAudioContext = uni.createInnerAudioContext();
const playing = ref(-1);
function play(src: string, index: number) {
  console.log(index === playing.value);
  if (index === playing.value) {
    innerAudioContext.stop();
  } else {
    innerAudioContext.stop();
    playing.value = index;
    innerAudioContext.src = src;
    innerAudioContext.play();
  }
}

function clickuserAvatar(e: Eps.BaseUserCommentEntity) {
  uni.navigateTo({
    url: `/pages/comment/listindex?userId=${e.userId}&show=1`,
  });
}

interface Icommenthistory {
  type?: string;
  context?: string;
  create_time?: any;
  show?: boolean;
  oldcontext?: string;
}

const commenthistorycomputed = computed(() => {
  const data: any[] = [];
  if (comment.value?.commenthistory.length) {
    forEach(comment.value.commenthistory, (v) => {
      data.push(v);
    });
  }
  let isdel = false;
  const isdelobj: Icommenthistory = {};
  if (comment.value?.isdelect) {
    isdel = true;
    isdelobj.type = "delect";
    isdelobj.create_time = comment.value.delecttime;
    isdelobj.show = true;
    isdelobj.context = "评价已被删除或隐藏";
  }

  const e = data.map((e: any, k: number) => {
    let _comm = data[k + 1];
    if (!_comm) _comm = comment.value;
    if (e.accurateScore !== _comm.accurateScore) {
      return {
        context: `评价从${e.accurateScore}星变为${_comm.accurateScore}星`,
        type: "score",
        create_time: e.update_time,
        show: true,
      } as Icommenthistory;
    } else if (e.content !== _comm.content) {
      return {
        context: _comm.content,
        oldcontext: e.content,
        type: "content",
        create_time: e.update_time,
        show: true,
      } as Icommenthistory;
    } else if (e.replyCount != _comm.replyCount) {
      return {
        context: `新增${Math.abs(
          Number(_comm.replyCount) - e.replyCount
        )}条回复`,
        type: "score",
        create_time: e.update_time,
        show: false,
      } as Icommenthistory;
    }
  });
  if (isdel) {
    e.push(isdelobj);
  }
  console.log(e);
  return e
    .filter((c) => c?.context && c.show)
    .sort(
      (a, b) => dayjs(b?.create_time).unix() - dayjs(a?.create_time).unix()
    );
});
const typemeituan = ["meituanwaimai", "eleme"];

const commentstepsoption = computed(() => {
  const y = dhms(
    Number(comment.value?.identifycomment?.starttimeconsuming || 0) * 1000
  )
    .filter((c) => c.t && c.name !== "s")
    .map((z) => {
      return z.t + z.name;
    })
    .join("");
  const r = dhms(
    Number(comment.value?.identifycomment?.identifytimeconsuming || 0) * 1000
  )
    .filter((c) => c.t && c.name !== "s")
    .map((z) => {
      return z.t + z.name;
    })
    .join("");
  const m = dhms(
    Number(comment.value?.identifycomment?.feedbacktimeconsuming || 0) * 1000
  )
    .filter((c) => c.t && c.name !== "s")
    .map((z) => {
      return z.t + z.name;
    })
    .join("");
  const 用户评价 = {
    name: "用户评价",
    time: typemeituan.includes(String(comment.value?.type))
      ? dayjs(comment.value?.feedbackTime).format("MM-DD")
      : dayjs(comment.value?.feedbackTime).format("MM-DD HH:mm"),
  };
  const 系统预警 = {
    name: "系统预警",
    time: y ? "+" + y : "",
  };
  const 鉴定 = {
    name: "鉴定",
    time: r ? "+" + r : "",
  };
  const 门店处理 = {
    name: "门店处理",
    time: m ? "+" + m : "",
  };
  const 完成 = {
    name: "完成",
    time: "",
  };
  if (isNumber(comment.value?.identifycommentstate)) {
    if (comment.value?.identifycomment?.issystem) {
      if (comment.value?.identifycomment?.isfeedback) {
        return [用户评价, 系统预警, 鉴定, 门店处理, 完成];
      } else {
        return [用户评价, 系统预警, 鉴定, 完成];
      }
    }
    if (comment.value?.identifycomment?.isfeedback) {
      return [用户评价, 鉴定, 门店处理, 完成];
    }

    return [用户评价, 鉴定, 完成];
  }
  return [用户评价, 完成];
});

onMounted(() => {
  innerAudioContext.onStop((e) => {
    playing.value = -1;
  });
  innerAudioContext.onEnded(() => {
    playing.value = -1;
  });
});
onPullDownRefresh(() => {
  start()
    .then((e) => {
      uni.stopPullDownRefresh();
    })
    .catch((f) => {
      uni.showToast({
        duration: 2000,
        title: f,
      });
      uni.stopPullDownRefresh();
    });
});

async function start() {
  comment.value = await apiget("/wechat/comment/info", {
    id: id.value,
  });
  if (comment.value) {
    comment.value.identifycommentstate = comment.value.identifycomment?.state;
    commentuser.value = comment.value?.commentuser;
    commentuserwatch.value = uniqBy(
      comment.value?.commentuserwatch.filter((c: any) => c.tenant_user?.user),
      (e) => {
        return e.tenant_user?.id;
      }
    );
    commenthistory.value = comment.value?.commenthistory;
    commentfeedback.value = comment.value?.commentfeedback;
  }

  api<Eps.identifylabelEntity[]>("/wechat/identifylabel/list")
    .then((e) => {
      identifylabel.value = e;
    })
    .catch((f) => {
      uni.showToast({
        icon: "error",
        title: f,
        duration: 2000,
      });
    });
}

const commentsteps = computed(() => {
  if (isNumber(comment.value?.identifycommentstate)) {
    if (comment.value?.state === "待鉴定") {
      return 1;
    } else if (comment.value?.state === "待反馈") {
      return 2;
    } else {
      return commentstepsoption.value.length;
    }
  } else {
    return 1;
  }
});

function navigateback() {
  uni.navigateBack({
    delta: 1,
    success() {
      console.log("success");
    },
    fail() {
      uni.switchTab({
        url: "/pages/comment/index",
      });
    },
  });
}

wx.showShareMenu({
  withShareTicket: true,
});
</script>

<style scoped lang="scss">
.commentinfo {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: $uni-bg-def1;
  padding-bottom: 6vh;

  .header {
    width: 100%;
    padding-top: 30rpx;
    padding-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;

    .poiName {
      height: 25px;
      color: #000;
      font-size: 18px;
      margin-bottom: 30rpx;
    }

    .steps {
      width: 100%;
    }
  }

  .resultstime {
    background-color: $uni-text-color-inverse;
    display: flex;
    flex-direction: column;
    padding: 32rpx;
    gap: 24rpx;

    .header-avatar {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;

      .header_right {
        flex: 1;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .top {
          height: 43rpx;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          font-weight: 600;
        }

        .top2 {
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex-wrap: wrap;
          font-size: 24rpx;
          color: rgba(170, 170, 170, 1);
        }
      }
    }

    .resultstime-text {
      .resultstime-title {
        color: rgba(51, 51, 51, 1);
        font-size: 28rpx;
        font-weight: 600;
      }

      .resultstime-context {
        color: rgba(102, 102, 102, 1);
        font-size: 24rpx;
      }
    }
  }
}

.resultstime-button {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 46rpx;
}

.w100 {
  width: 100%;
  background-color: $uni-text-color-inverse;
  padding-top: 30rpx;
  padding-bottom: 30rpx;
}

.header-icon {
  display: flex;
  flex-wrap: wrap;
  padding-left: 32rpx;
  padding-right: 32rpx;
  margin-bottom: 12px;
  gap: 12rpx;

  .header-icon-text {
    display: inline-block;
    font-weight: 600;
  }
}

.header-context {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.header-button {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  padding-left: 32rpx;
  padding-right: 32rpx;
}

.bg-commenthistorycomputed {
  color: #ff724c;
  background-color: rgba(255, 114, 76, 0.1);
  width: 60vw;
  height: 80rpx;
  font-size: 28rpx;
  font-weight: 600;
  text-align: center;
  line-height: 80rpx;
  border-radius: 8rpx;
  display: block;
  margin: 0 auto;
}

.context-voice {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  height: 60rpx;
  gap: 12px;

  .context-voice-mic {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background-color: rgba(253, 117, 76, 1);
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 12rpx;
  }
}

.info-footer {
  width: 100%;
  margin-top: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.uv-text1 {
  // color: #fff;
  font-size: 24rpx;
}
</style>

<style>
/* #steps .uv-steps-item__wrapper {
    background-color: rgba(253, 117, 76, 1) !important;
} */

/* #steps .uv-text__value {
    color: #fff;
} */

/* #steps .uv-text__value--main {
    color: #fff;

} */
</style>
